<template>
  <button
    :class="buttonClass"
    :type="htmlType"
    :disabled="disabled || loading"
    @click="handleClick"
  >
    <!-- 加载图标 -->
    <span v-if="loading" class="ui-button__loading">
      <svg class="ui-button__loading-icon" viewBox="0 0 1024 1024">
        <path
          d="M512 1024c-69.1 0-136.2-13.5-199.3-40.2C251.7 958 197 921 150.9 874.9c-46.1-46.1-83.1-100.8-109.8-162.7C13.5 648.2 0 581.1 0 512c0-69.1 13.5-136.2 40.2-199.3C66 251.7 103 197 149.1 150.9c46.1-46.1 100.8-83.1 162.7-109.8C375.8 13.5 442.9 0 512 0c69.1 0 136.2 13.5 199.3 40.2C772.3 66 827 103 873.1 149.1c46.1 46.1 83.1 100.8 109.8 162.7C1010.5 375.8 1024 442.9 1024 512c0 69.1-13.5 136.2-40.2 199.3C958 772.3 921 827 874.9 873.1c-46.1 46.1-100.8 83.1-162.7 109.8C648.2 1010.5 581.1 1024 512 1024zM512 92c-231.4 0-420 188.6-420 420s188.6 420 420 420 420-188.6 420-420S743.4 92 512 92z"
        />
        <path
          d="M512 772c-143.2 0-260-116.8-260-260s116.8-260 260-260 260 116.8 260 260-116.8 260-260 260z m0-460c-110.3 0-200 89.7-200 200s89.7 200 200 200 200-89.7 200-200-89.7-200-200-200z"
        />
      </svg>
    </span>

    <!-- 左侧图标 -->
    <span v-if="icon && !loading" class="ui-button__icon ui-button__icon--left">
      <slot name="icon">
        {{ icon }}
      </slot>
    </span>

    <!-- 按钮内容 -->
    <span v-if="$slots.default" class="ui-button__content">
      <slot />
    </span>

    <!-- 右侧图标 -->
    <span
      v-if="icon && !loading && iconPosition === 'right'"
      class="ui-button__icon ui-button__icon--right"
    >
      <slot name="icon">
        {{ icon }}
      </slot>
    </span>
  </button>
</template>

<script setup lang="ts">
import { computed, useSlots } from "vue"
import { buttonProps, type ButtonEmits } from "./types"

// 定义组件名称
defineOptions({
  name: "UiButton",
})

// 定义Props
const props = defineProps(buttonProps)

// 定义事件
const emit = defineEmits<ButtonEmits>()

// 获取slots
const slots = useSlots()

// 计算按钮样式类
const buttonClass = computed(() => {
  const classes = ["ui-button"]

  // 按钮类型
  classes.push(`ui-button--${props.type}`)

  // 按钮尺寸
  classes.push(`ui-button--${props.size}`)

  // 按钮形状
  if (props.shape !== "default") {
    classes.push(`ui-button--${props.shape}`)
  }

  // 按钮状态
  if (props.disabled) {
    classes.push("ui-button--disabled")
  }

  if (props.loading) {
    classes.push("ui-button--loading")
  }

  if (props.danger) {
    classes.push("ui-button--danger")
  }

  if (props.block) {
    classes.push("ui-button--block")
  }

  if (props.ghost) {
    classes.push("ui-button--ghost")
  }

  // 只有图标没有文字
  if (props.icon && !slots.default) {
    classes.push("ui-button--icon-only")
  }

  return classes
})

// 处理点击事件
const handleClick = (event: MouseEvent) => {
  if (props.disabled || props.loading) {
    return
  }
  emit("click", event)
}
</script>

<script lang="ts">
export default {
  name: "UiButton",
}
</script>

<style>
@import "./Button.css";
</style>
